// 
package com.seguriapp.activities;

import java.util.List;

import android.content.Intent;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.Toast;

import com.seguriapp.R;
import com.seguriapp.adapters.LstEntityAdapter;
import com.seguriapp.controllers.EntityController;
import com.seguriapp.entities.POIMarker;
import com.seguriapp.util.ActionItem;
import com.seguriapp.util.Constants;
import com.seguriapp.util.GPS;
import com.seguriapp.util.QuickAction;

/**
 * TODO(pjohnson): Insert description
 * 
 * @author Pablo Johnson (pjohnson@avantica.net)
 */
public class EntityListFragmentActivity extends FragmentActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_complaint_list);
		if (savedInstanceState == null) {
			Fragment newFragment = EntityListFragment.newInstance();
			FragmentTransaction ft = getSupportFragmentManager()
					.beginTransaction();
			ft.add(R.layout.fragment_entity_list, newFragment).commit();
		}
	}

	public static class EntityListFragment extends BaseFragment {

		static EntityListFragment newInstance() {
			final EntityListFragment f = new EntityListFragment();
			return f;
		}

		private ListView listEntities;
		protected POIMarker selectedMarker;
		protected int mSelectedRow;
		protected ImageView mMoreIv;
		private String typeId;
		private static final int SHOW_IN_MAP = 10;
		private static final int MAKE_CALL = 20;
		private static final int MAKE_COMPLAINT = 30;
		private static final String ANDROID_INTENT_ACTION_VIEW = "android.intent.action.VIEW";

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
			super.onCreateView(inflater, container, savedInstanceState);
			setHasOptionsMenu(true);
			typeId = getActivity().getIntent().getStringExtra("typeId");
			
			return inflater.inflate(R.layout.fragment_entity_list, container,
					false);
		}

		@Override
		public void onResume() {
			super.onResume();

			final ActionItem addItem = new ActionItem(SHOW_IN_MAP,
					getString(R.string.show_route), getResources().getDrawable(
							R.drawable.ic_add));
			final ActionItem acceptItem = new ActionItem(MAKE_CALL,
					getString(R.string.make_call), getResources().getDrawable(
							R.drawable.ic_accept));
			final ActionItem uploadItem = new ActionItem(MAKE_COMPLAINT,
					getString(R.string.make_complaint), getResources()
							.getDrawable(R.drawable.ic_up));
			final QuickAction mQuickAction = new QuickAction(getActivity());

			mQuickAction.addActionItem(addItem);
			mQuickAction.addActionItem(acceptItem);
			mQuickAction.addActionItem(uploadItem);

			listEntities = (ListView) getActivity().findViewById(
					R.id.entity_list);

			// setup on dismiss listener, set the icon back to normal
			mQuickAction
					.setOnDismissListener(new PopupWindow.OnDismissListener() {

						@Override
						public void onDismiss() {
							mMoreIv.setImageResource(R.drawable.ic_list_more);
						}
					});

			listEntities.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					// mSelectedRow = position; //set the selected row
					selectedMarker = (POIMarker) listEntities
							.getItemAtPosition(position);
					mQuickAction.show(view);
					mSelectedRow = position;
					// change the right arrow icon to selected state
					mMoreIv = (ImageView) view.findViewById(R.id.i_more);
					mMoreIv.setImageResource(R.drawable.ic_list_more_selected);
				}
			});

			// setup the action item click listener
			mQuickAction
					.setOnActionItemClickListener(new QuickAction.OnActionItemClickListener() {

						@Override
						public void onItemClick(QuickAction quickAction,
								int pos, int actionId) {
							final ActionItem actionItem = quickAction
									.getActionItem(pos);
							if (actionId == SHOW_IN_MAP) { // Add item selected

								final GPS gps = new GPS();
								final Location location = gps
										.getCurFix(getActivity());

								final double currentLatitude = location
										.getLatitude();
								final double currentLongitude = location
										.getLongitude();
								String toDirection = selectedMarker
										.getLatitude()
										+ Constants.COLON
										+ selectedMarker.getLongitude();
								;
								String fromDirection = currentLatitude
										+ Constants.COLON + currentLongitude;
								gps.removeUpdates(gps);
								Intent browserIntent = new Intent(
										ANDROID_INTENT_ACTION_VIEW,
										Uri.parse("http://maps.google.com/maps?daddr="
												+ toDirection
												+ "&saddr="
												+ fromDirection));
								startActivity(browserIntent);

							} else if (actionId == MAKE_CALL) {
								final String posted_by = "014311755";

								String uri = "tel:" + posted_by.trim();
								Intent intent = new Intent(Intent.ACTION_CALL);
								intent.setData(Uri.parse(uri));
								startActivity(intent);
							} else if (actionId == MAKE_COMPLAINT) {
								final Intent complaintIntent = new Intent();
								final Bundle bundle = new Bundle();
								bundle.putString("entityId", String
										.valueOf(selectedMarker.getEntityId()));
								complaintIntent.putExtras(bundle);
								complaintIntent.setClass(getActivity(),
										ComplaintActivity.class);
								startActivity(complaintIntent);
							} else {
								Toast.makeText(
										getActivity(),
										actionItem.getTitle()
												+ " item selected on row "
												+ mSelectedRow,
										Toast.LENGTH_SHORT).show();
							}
						}
					});

			obtenerEntidades();

		}

		private void obtenerEntidades() {
			mostrarDialogoEsperaSinCancel(getActivity());
			new Thread(new Runnable() {
				public void run() {
					final LocationManager service = (LocationManager) getActivity()
							.getSystemService(LOCATION_SERVICE);
					final Criteria criteria = new Criteria();
					final String provider = service.getBestProvider(criteria,
							false);
					final Location location = service
							.getLastKnownLocation(provider);

					final EntityController eController = new EntityController(
							getActivity());
					final List<POIMarker> items = eController.getEntityList(
							location.getLatitude(), location.getLongitude(), typeId);
					getActivity().runOnUiThread(new Runnable() {

						@Override
						public void run() {
							if (items != null) {
								listEntities.setAdapter(new LstEntityAdapter(
										getActivity(),
										R.layout.list_entity_item, items));
							}
							ocultarDialogo();
						}
					});
				}
			}).start();

		}
	}

}
